﻿/**
 * Peter
 * Created by: Peter Development Team
 *    http://peter.codeplex.com/
 * 
 * GNU General Public License version 2 (GPLv2)
 *    http://peter.codeplex.com/license
 **/

using System.ComponentModel;
using System.Windows;
using Peter.Ftp.Data;
using Peter.Ftp.Logic;

namespace Peter.Ftp.View
{
   /// <summary>
   /// Interaction logic for ViewFtpOptions.xaml
   /// </summary>
   public partial class ViewFtpOptions
   {
      private OptionsFtp m_Model;
      private FtpConnectionData m_ConnectionData;
      private bool m_OkToUpdate = true;

      /// <summary>
      /// Initializes a new ftp options view.
      /// </summary>
      public ViewFtpOptions ()
      {
         InitializeComponent ();
         this.DataContextChanged += this.OnDataContextChanged;
      }

      /// <summary>
      /// Occurs when the data context changes.
      /// </summary>
      /// <param name="sender">this</param>
      /// <param name="e">DependencyPropertyChangedEventArgs</param>
      private void OnDataContextChanged (object sender, DependencyPropertyChangedEventArgs e)
      {
         this.DataContextChanged -= this.OnDataContextChanged;
         this.m_Model = (OptionsFtp)this.DataContext;
         this.m_Model.PropertyChanged += this.OnModelPropertyChanged;
      }

      private void OnModelPropertyChanged (object sender, PropertyChangedEventArgs e)
      {
         if (e.PropertyName == "SelectedConnection")
         {
            if (this.m_ConnectionData != null)
               this.m_ConnectionData.PropertyChanged -= this.OnModelPropertyChanged;

            this.m_ConnectionData = this.m_Model.SelectedConnection;
            if (this.m_ConnectionData != null)
            {
               this._Password.Password = this.m_ConnectionData.Password;
               this.m_ConnectionData.PropertyChanged += this.OnModelPropertyChanged;
            }
         }
         else if (e.PropertyName == "Password" && this.m_OkToUpdate)
         {
            this._Password.Password = this.m_ConnectionData.Password;
         }
      }

      /// <summary>
      /// Occurs when the password changes.
      /// </summary>
      /// <param name="sender">PasswordBox</param>
      /// <param name="e">RoutedEventArgs</param>
      private void PasswordChanged (object sender, RoutedEventArgs e)
      {
         if (this.m_ConnectionData != null)
         {
            this.m_OkToUpdate = false;
            this.m_ConnectionData.Password = this._Password.Password;
            this.m_OkToUpdate = true;
         }
      }
   }
}
